package com.lingjtx.im.core.handle;

import com.lingjtx.common.core.constant.RedisConfig;
import com.lingjtx.common.redis.service.IRedisService;
import com.lingjtx.im.core.common.ChannelPool;
import com.lingjtx.im.core.common.SessionManager;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@ChannelHandler.Sharable
@Component
public class HeartbeatHandler extends ChannelInboundHandlerAdapter {

    private final IRedisService redisService;

    public HeartbeatHandler(IRedisService redisService) {
        this.redisService = redisService;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        if (evt instanceof IdleStateEvent) {
            log.warn("连接超时断开：{}", ctx.channel().remoteAddress());
            SessionManager.removeSession(ctx.channel(), redisService);
            redisService.delete(RedisConfig.IM_USER_ONLINE + ChannelPool.getUserId(ctx.channel()));
            ctx.close();
        }
    }

}
